﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Navigation;
using FanaticInstaller.Helpers;

namespace FanaticInstaller.Utils
{
    public static class NavigationRegister
    {
        private static Dictionary<FrameworkElement, NavigationService> _frameworkNavigationPairs = new Dictionary<FrameworkElement, NavigationService>();

        public static void Navigatlize(FrameworkElement host, NavigationService navigationService)
        {
            if (!_frameworkNavigationPairs.ContainsKey(host))
                _frameworkNavigationPairs.Add(host, navigationService);
            host.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(NavigateCallback));
        }

        public static void Navigatlize(NavigationWindow host)
        {
            Navigatlize(host, host.NavigationService);
        }

        public static void Navigatlize(Frame frame)
        {
            Navigatlize(frame, frame.NavigationService);
        }

        public static void NavigateCallback(object sender, RoutedEventArgs args)
        {
            if (sender is FrameworkElement host)
            {
                if (_frameworkNavigationPairs.TryGetValue(host, out NavigationService navigationService))
                {
                    if (args.OriginalSource is ButtonBase button)
                    {
                        var uri = NavigationHelper.GetNavigationUri(button);
                        if (uri == null) return;
                        navigationService.Navigate(uri);
                    }
                }
            }

        }
    }
}
